<template>
    <div class="approval-container">
      <!-- 搜索条件区域 -->
      <div class="search-wrapper">
        <el-form :inline="true" :model="searchForm" ref="searchForm" class="search-form" label-width="85px" style="text-align: left">
          <div>
            <el-row>
              <el-col :span="6">
                <el-form-item label="菜品编号" prop="foodCode">
                  <el-input v-model="searchForm.foodCode" placeholder="菜品编号" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6" style="text-align: center;">
                <el-form-item label="菜品名称" prop="foodName">
                  <el-input v-model="searchForm.foodName" placeholder="菜品名称" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6" style="text-align: center;">
                <el-form-item label="食材清单" prop="supplierName">
                  <!-- <el-input v-model="searchForm.supplierName" placeholder="食材清单" clearable></el-input> -->
                  <el-select 
                      v-model="searchForm.params.ingredientsId" 
                      placeholder="请选择"
                      clearable
                      style="width: 100%;"
                    >
                      <el-option
                        v-for="items in ingredientList"
                        :key="items.ingredientsId"
                        :label="items.ingredientsName"
                        :value="items.ingredientsId"
                      ></el-option>
                    </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" style="text-align: right;">
                <el-form-item label="现售价" prop="price">
                  <el-input v-model="searchForm.price" placeholder="价格" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
  
          <div style="margin-top: 10px;">
            <el-row>
                <el-col :span="6">
                <el-form-item label="原价" prop="originalPrice">
                  <el-input v-model="searchForm.originalPrice" placeholder="原价" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6" style="text-align: center;" >
                <el-form-item label="创建人" prop="createBy">
                  <el-input v-model="searchForm.createBy" placeholder="创建人" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6" style="text-align: center;">
                <el-form-item label="创建日期" prop="createTime">
                  <el-date-picker v-model="searchForm.createTime" type="date" value-format="yyyy-MM-dd"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6" style="text-align: right;">
                <div class="search-actions">
                  <el-button style="background-color: #4C6EE2;color: white;" size="small" @click="handleSearch">搜索</el-button>
                  <el-button size="small" @click="resetSearch">重置</el-button>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </div>
  
      <!-- 审批状态筛选 -->
      <div class="status-filter" style="display: flex;justify-content: space-between;">
        <el-radio-group v-model="radio" style="margin-top: 9px;margin-left: 17px;" @input="inputGroup">
          <el-radio :label="1">全部</el-radio>
          <el-radio :label="2">正常</el-radio>
          <el-radio :label="3">淘汰</el-radio>
          <el-radio :label="4">停用</el-radio>
          <el-radio :label="5">早餐</el-radio>
          <el-radio :label="6">午餐</el-radio>
          <el-radio :label="7">晚餐</el-radio>
        </el-radio-group>
        <div style="position: relative;">
          <div style="position: absolute;top: 40px;width: 170px;height: 330px;left: 0; background-color: white; border-radius: 10px;z-index: 9999;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);padding: 10px;overflow: auto;padding-top: 20px;" v-if="columnShow">
            <!-- <div style="text-align: right;margin-bottom: 10px;">
              <i class="el-icon-close" @click="columnShow = false"></i>
            </div> -->
            <div v-for="(item,index) in dictData" :key="index" style="display: flex;justify-content: space-between;padding-bottom: 15px;">
                <div style="font-size: 15px;">
                   {{ item.dictLabel }}
                </div>

                <div>
                  <el-switch
                  @change="(e)=>onchangeSwitch(e,item)"
                    v-model="item.dictValue"
                    active-value="1"
                    inactive-value="0">
                  </el-switch>
                </div>
            </div>
          </div>
          <el-button type="primary" size="small" plain @click="columnShow = !columnShow" >显示列</el-button>

        
          
          <el-button type="primary" size="small" plain icon="el-icon-plus" @click="handleAdd" v-hasPermi="['food:dish:add']">新增</el-button>
          <el-button type="success" size="small" plain icon="el-icon-edit" @click="handleBatchEdit" v-hasPermi="['food:dish:edit']">修改</el-button>
          <el-button type="info" size="small" plain icon="el-icon-upload2" @click="handleImport">导入</el-button>
          <el-button type="warning" size="small" plain icon="el-icon-download" @click="handleExport">导出</el-button>
          <el-button type="danger" size="small" plain icon="el-icon-delete-solid" @click="handleBatchDelete" v-hasPermi="['food:dish:remove']">删除</el-button>
        </div>
      </div>
  
      <!-- 审批数据表格 -->
      <div class="table-wrapper">
        <el-table 
          :data="tableData" 
          style="width: 100%" 
          v-loading="loading"
          :header-cell-style="{ background: '#f8f8f9' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center"></el-table-column>
          <el-table-column prop="foodCode" label="菜品编号" width="150"></el-table-column>
          <el-table-column prop="foodName" label="菜品名称" width="200" align="left">
            <template slot-scope="scope">

              <div style="display: flex;">
                <div>
                  {{ scope.row.foodName }}
                </div>
                <div v-if="scope.row.huisType == 1" style="margin-top: 0px;margin-left: 5px;">
                <!-- <img src="@/assets/images/pig.png"  alt="" style="width: 15px;height: 15px;"> -->
                🐷
               </div>
                <div style="margin-top: -2px;margin-left: 5px;padding-top: 5px;">
                  <span v-for="value in Number(scope.row.peType)">
                    🌶
                  </span>
                  <!-- <img src="@/assets/images/chili.png" v-for="value in Number(scope.row.peType)" alt="" style="width: 8px;height: 15px;margin-top: 5px;"></img> -->
                </div>

               
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="image" label="菜品图片" width="150" align="left">
            <!-- <template slot-scope="scope">
              <el-image 
                v-if="scope.row.image"
                style="width: 30px; height: 30px;border-radius: 50%;"
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"
                fit="cover"
              ></el-image>
              <span v-else>无图片</span>
            </template> -->
            <template slot-scope="scope">
    <div v-if="scope.row.image && scope.row.image.length" style="display: flex; flex-wrap: wrap; gap: 10px;">
      <div v-for="(file, index) in parseFileList(scope.row.image)" :key="index">
        <!-- 图片显示缩略图 -->
        <div v-if="isImage(file)" style="display: inline-block;">
          <el-image 
            style="width: 30px; height: 30px; margin-right: 5px;border-radius: 50%;"
            :src="file.url" 
            fit="cover"
            :preview-src-list="getPreviewList(scope.row.image)">
          </el-image>
        </div>
        <!-- 非图片显示文件链接 -->
        <div v-else style="display: inline-block;">
          <el-link 
            type="primary" 
            :href="file.url" 
            target="_blank"
            style="margin-right: 10px;">
            <el-icon><Document /></el-icon>
            {{ file.name || '下载文件' }}
          </el-link>
        </div>
      </div>
    </div>
    <span v-else>-</span>
  </template>
          </el-table-column>
          <el-table-column prop="ingredients" width="180" label="食材清单" align="left" v-if="tableColumn.食材清单 == 1">
              <!-- 自定义表头 -->
              <!-- <template slot="header">
                <div class="custom-header">
                <span class="header-title">食材清单</span>
                <div 
                v-if="tabhanderObj"
                  class="status-indicator" 
                  :class="tabhanderObj.inType ? 'enabled' : 'disabled'"
                >
                  <span class="status-dot"></span>
                  <span class="status-text">
                    {{ tabhanderObj.inType ? "已开启" : "未开启" }}
                  </span>
                </div>
              </div>
              </template> -->
              <!-- 自定义单元格内容 -->
              <template slot-scope="scope">
                <span v-for="(item,index) in scope.row.foodIngredientsDishList" :key="index">
                  {{ item.ingredientsName }}
                </span>
              </template>
            </el-table-column>
          <el-table-column prop="allergy" label="过敏源" align="left" v-if="tableColumn.过敏源 == 1"></el-table-column>
          <el-table-column prop="heat" align="left" label="热量" v-if="tableColumn.热量 == 1">
          </el-table-column>
          <!-- <el-table-column prop="huisType" align="left" label="回民标识">
              <template slot-scope="scope" v-if="scope.row.huisType == 1">
                <div >
                <img src="@/assets/images/pig.png"  alt="" style="width: 40px;height: 30px;">
               </div>
            </template>
          </el-table-column> -->
          <el-table-column prop="price" label="现售价" align="right" v-if="tableColumn.现售价 == 1">
            <template slot-scope="scope" v-if="scope.row.price">
              ¥{{ scope.row.price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="originalPrice" label="原价" align="right" v-if="tableColumn.原价 == 1">
            <template slot-scope="scope" v-if="scope.row.originalPrice">
              ¥{{ scope.row.originalPrice.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="saleAllNum" label="累计销量" align="left" v-if="tableColumn.累计销量 == 1">
              <template slot-scope="scope">
                {{ scope.row.saleAllNum < 0 ? 0 : scope.row.saleAllNum }}
              </template>
            </el-table-column>
          <el-table-column prop="score" label="淘汰分值" align="left"></el-table-column>
          <el-table-column prop="validDays" label="开放时间" width="190" align="left" show-overflow-tooltip>
          <template slot-scope="scope">
            <div style="" v-if="scope.row.day1 != null && scope.row.day1 != undefined">
              <span v-for="(item,index) in 7" :key="index">
                {{ scope.row["day" + (index + 1)] == 1 ? (openingHoursList[index].label + "、") : "" }}
              </span>
            </div>
          </template>
        </el-table-column>
          <el-table-column prop="portion" label="规格" align="left" show-overflow-tooltip v-if="tableColumn.规格 == 1"></el-table-column>
          <el-table-column prop="taste" align="left" label="口味"  width="150" show-overflow-tooltip v-if="tableColumn.口味 == 1">
            <!-- <template slot="header">
                <div class="custom-header">
                <span class="header-title">口味</span>
                <div 
                v-if="tabhanderObj"
                  class="status-indicator" 
                  :class="tabhanderObj.taste ? 'enabled' : 'disabled'"
                >
                  <span class="status-dot"></span>
                  <span class="status-text">
                    {{ tabhanderObj.taste ? "已开启" : "未开启" }}
                  </span>
                </div>
              </div>
              </template> -->
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template slot-scope="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" width="100" align="center">
            <template slot-scope="scope">
              <el-tag :type="moldList[scope.row.type -1].label">
                {{ moldList[scope.row.type -1].label }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="菜品描述" align="left" show-overflow-tooltip></el-table-column>
                  <el-table-column prop="sort" label="排序"></el-table-column>

          <el-table-column prop="createBy" label="创建人" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center" width="200"></el-table-column>
          <el-table-column prop="remark" label="备注" width="160" align="left" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" width="150" align="center" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleEdit(scope.row)" style="color: #4C6EE2;" v-hasPermi="['food:dish:edit']">编辑</el-button>
              <el-button type="text" size="small" @click="handleDelete(scope.row)" style="color: #4C6EE2;" v-hasPermi="['food:dish:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="pagination">
          <!-- <el-pagination 
            @size-change="handleSizeChange" 
            @current-change="handleCurrentChange"
            :current-page="pagination.pageNum" 
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize" 
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
          ></el-pagination> -->
          <pagination v-show="pagination.total > 0" :total="pagination.total" :page.sync="pagination.pageNum" :limit.sync="pagination.pageSize" @pagination="fetchData" />

        </div>
      </div>
  
      <!-- 新增/编辑弹框 -->
      <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="50%"
        style="border-radius: 10px;"
        @close="resetForm"
      >
      <template #title>
      <div class="custom-dialog-title">
        <div style="display: flex;border-bottom: 1px solid rgba(0, 0, 0, 0.05);padding-bottom: 20px;padding-left: 30px;">
          <div style="background-color: #4C6EE2;border-radius: 20px;width: 4px;margin-right: 8px;height: 20px;margin-top: 6.5px;">
          </div>
          <span class="title-text" style="font-family: Source Han Sans;
          font-size: 20px;
          font-weight: 500;
          line-height: 31px;
          text-align: center;
          letter-spacing: normal;
          color: #3D3D3D;">{{ dialogTitle }}</span>
        </div>
      </div>
    </template>
    <div style="
        font-family: Source Han Sans;
        font-size: 20px;
        font-weight: 500;
        line-height: 31px;
        margin-left: 30px;
        display: flex;
        letter-spacing: normal;
        color: #3D3D3D;">
        <!-- <svg-icon style="margin-right: 10px;" icon-class="@/assets/images/updatesvn.svg" class="item-icon" /> -->
        <img src="@/assets/images/updatesvn.svg" alt="" style="padding-right: 5px;">
        基本信息
    </div>
        <el-form
          ref="foodForm"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="dialogN"
          label-position="top"
          style="padding: 30px;padding-top: 10px;"
          size="medium"
        >
 
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="菜品名称" prop="foodName">
                <el-input v-model="form.foodName" placeholder="请输入菜品名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="热量（千卡）" prop="heat">
                <el-input v-model="form.heat" placeholder="请输入热量" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="口味" prop="taste">
                <el-input v-model="form.taste" placeholder="请输入口味" clearable />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
                <el-form-item label="现售价" prop="price">
                <el-input v-model="form.price" :min="0" :precision="2" placeholder="请输入现售价" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="原价" prop="originalPrice">
                <el-input v-model="form.originalPrice" :min="0" placeholder="请输入原价" :precision="2" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="规格" prop="portion">
                <el-input v-model="form.portion" placeholder="请输入规格" clearable />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
            <el-form-item label="开放时间" prop="openingHours">
              <el-select v-model="form.openingHours" multiple placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="(item,index) in openingHoursList"
                  :key="index"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
            <el-col :span="8">
                <el-form-item label="状态" prop="status">
                  <el-select v-model="form.status" placeholder="请选择" style="width: 100%;">
                      <el-option
                        v-for="(item,index) in statusList"
                        :key="index"
                        :label="item.label"
                        :value="String(item.value)"
                        >
                      </el-option>
                  </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="类型" prop="type">
                <el-select v-model="form.type" placeholder="请选择" style="width: 100%;">
                    <el-option
                      v-for="(item,index) in moldList"
                      :key="index"
                      :label="item.label"
                      :value="Number(item.value)">
                    </el-option>
              </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
                
            </el-col>
          </el-row>

          <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="最大供应量" prop="num">
              <el-input v-model="form.num" type="number"  :min="0" placeholder="请输入最大供应量" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最大限购(-1不限)" prop="limitPerUser">
              <el-input-number v-model="form.limitPerUser" controls-position="right" :min="-1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          
          <el-col :span="8">
            <el-form-item label="辣度" prop="peType">
              <el-input-number v-model="form.peType" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="回民标识" prop="huisType">
              <!-- <el-input v-model="form.huisType"   :min="0" placeholder="请输入最大供应量" style="width: 100%" /> -->
              <el-switch
                v-model="form.huisType"
                active-color="#4C6EE2"
                inactive-color="#ff4949"
                active-text="开启"
                inactive-text="关闭"
                :active-value="1"
                :inactive-value="0"
                >
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>

          <div style="font-size: 20px;font-weight: 600;padding: 12px 0;display: flex;">
        <img src="@/assets/images/updatesvn.svg" alt="" style="margin-top: -6px;padding-right: 5px;">

          菜品信息
          <el-button plain style="background-color: rgb(237, 240, 252);color: #4C6EE2;border: 1px solid #4C6EE2;margin-left: 7px;margin-top: -3px;" @click="addIngredients">添加食材</el-button>
        </div>
        <!-- {{ form.foodIngredientsDishList }}  -->
        <el-row :gutter="20" v-for="(item,index) in form.foodIngredientsDishList" :key="index">
  <el-col :span="8">
    <el-form-item 
      label="食材" 
     
    >
      <el-select 
        v-model="item.ingredientsId" 
        clearable 
        placeholder="请选择" 
        style="width: 100%;"
        @change="handleIngredientChange(index)"
      >
        <el-option
          v-for="items in ingredientList.filter(el=>el.status != 1)"
          :key="items.ingredientsId"
          :label="items.ingredientsName"
          :value="items.ingredientsId"
          :disabled="isIngredientDisabled(items.ingredientsId, index)"
        >
        <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
            <span>{{ items.ingredientsName }}</span>
            <span>供应商：{{ items.supplierName }}</span>
          </div>
      </el-option>
      </el-select>
    </el-form-item>
  </el-col>
  <el-col :span="13">
    <el-form-item 
      label="用量"
      
    >
      <el-input 
        v-model="item.num" 
        :min="0" 
        clearable 

        placeholder="请输入用量" 
        :precision="2" 
        style="width: 61%" 
      />
      <!-- 克（g） -->
      <!-- {{ item.unit }} -->
        <span v-if="ingredientList.filter(el=>el.ingredientsId == item.ingredientsId).length > 0 && ingredientList.filter(el=>el.ingredientsId == item.ingredientsId)[0].unit">
          {{ dict.type.foot_ingredient_type.filter(el=>el.value == ingredientList.filter(el=>el.ingredientsId == item.ingredientsId)[0].unit)[0].label }}
        <!-- {{ ingredientList.filter(el=>el.ingredientsId == item.ingredientsId)[0].unit }} -->

        </span>
      <i class="el-icon-delete" v-if="index != 0" @click="deleteFoodItems(item,index)"></i>
    </el-form-item>
  </el-col>
  <!-- <el-col :span="8">
    <el-form-item 
      label="单位"
      :prop="`foodIngredientsDishList.${index}.num`"
      :rules="{
        required: true,
        message: '请选择单位',
        trigger: 'blur'}"
    >
      <el-select v-model="value" placeholder="请选择">
        <el-option
        style="width: 100%;"
          v-for="item in dict.type.foot_ingredient_type"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-input 
        v-model="item.num" 
        :min="0" 
        placeholder="请输入用量" 
        :precision="2" 
        style="width: 100%" 
      />
      <i class="el-icon-delete" v-if="index != 0" @click="deleteFoodItems(item,index)"></i>
    </el-form-item>
  </el-col> -->
</el-row>
       

          
          <el-form-item label="菜品描述" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="3"
              placeholder="请输入菜品描述"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="过敏源" prop="allergy">
            <el-input
              v-model="form.allergy"
              type="textarea"
              :rows="2"
              placeholder="请输入过敏源信息，多个用逗号分隔"
            />
          </el-form-item>


          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              :rows="2"
              placeholder="请输入备注信息"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="菜品图片" prop="image" >
                <el-upload
                  action="#"
                  list-type="picture-card"
                  :auto-upload="false"
                  :on-change="handleImageChange"
                  :file-list="fileList"
                  :before-upload="beforeUpload"
                  :show-file-list="true"
                  :on-remove="handleRemove"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
            </el-col>
          </el-row>
        </el-form>

        <div slot="footer" class="dialog-footer" style="text-align: center;">

          <el-button @click="dialogVisible = false" style="background-color: white;color: #4C6EE2;border: 1px solid #4C6EE2;">取 消</el-button>
          <el-button type="primary" @click="handleSubmit" style="background-color: #4C6EE2;color: white;" :loading="submitting">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    </div>
  </template>
  
  <script>
  import { getList, dishAdd, dishUpdate, deleteDish,uploading } from '@/api/cuisine'
  import { getList as getlists} from '@/api/ingredient'
  import { getToken } from "@/utils/auth"
  import { listData, getData, delData, addData, updateData } from "@/api/system/dict/data"
import nameding from "@/plugins/download.js"

  export default {
    name: "DishManagement",
  dicts: ['foot_ingredient_type',"food_eat_type","cuisine_column"],
    data() {
      return {
        columnShow:false,
        ingredientList: [],
        dictData:[],
        searchForm: {
          foodCode: '',
          foodName: '',
          price: '',
          originalPrice: '',
          params: {
           ingredients: '',
          },
          createBy: '',
          createTime: ''
        },
        moldList: [
      {
        value: 1,
      label:"早餐"
      },
      {
        value: 2,
      label:"午餐"
      },
      {
        value: 3,
      label:"晚餐"
      }
      ],
        statusList: [
          {
            value: 0,
            label:"正常"
          },
          {
            value: 1,
            label:"停用"
          },
          {
            value: 2,
            label:"淘汰"
          }
        ],
        upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/food/dish/importData"
        },
        url: process.env.VUE_APP_BASE_API + "/food/upload",
        radio: 1,
        loading: false,
        tableData: [],
        openingHoursList: [
        { value: 1, label: "周一" },
        { value: 2, label: "周二" },
        { value: 3, label: "周三" },
        { value: 4, label: "周四" },
        { value: 5, label: "周五" },
        { value: 6, label: "周六" },
        { value: 7, label: "周日" }
      ],
        multipleSelection: [],
        pagination: {
          pageNum: 1,
          pageSize: 10,
          total: 0
        },
        dialogVisible: false,
        dialogTitle: '新增菜品',
        submitting: false,
        fileList: [],
        tableColumn:{},
        form: {
          foodName: '',
          image: '',
          peType: 0,
          huisType:0,
          openingHours:[],
          ingredients: '',
          allergy: '',
          calories: '',
          foodIngredientsDishList: [
            {
              ingredientsName: "",
              ingredientsId: "",
              ingredientsCode: "",
              foodId:""
            }
          ],
          price: null,
          originalPrice: null,
          sales: null,
          portion: '',
          taste: '',
          description: '',
          status: '0',
          createBy: '',
          createTime: '',
          remark: '',
        },
        tabhanderObj:{},
        rules: {
          foodCode: [
            { required: true, message: '请输入菜品编号', trigger: 'blur' }
          ],
          foodName: [
            { required: true, message: '请输入菜品名称', trigger: 'blur' }
          ],
          type: [
            { required: true, message: '请选择类型', trigger: 'blur' }
          ],
          // taste: [
          //   { required: true, message: '请输入口味', trigger: 'blur' }
          // ],
          // openingHours: [
          //   { required: true, message: '请选择开放时间', trigger: 'blur' }
          // ],
          // portion: [
          //   { required: true, message: '请输入规格', trigger: 'blur' }
          // ],
          sort: [
          { required: true, message: '请填写排序', trigger: 'blur' }
        ],
          num: [
            { required: true, message: '请输入最大供应量', trigger: 'blur' }
          ],
          // allergy: [
          //   { required: true, message: '请输入过敏源', trigger: 'blur' }
          // ],
          // image: [
          //   { required: true, message: '请上传图片', trigger: 'changes' }
          // ],
          
          'foodIngredientsDishList': [
            { 
              validator: (rule, value, callback) => {
                if (!value || value.length === 0) {
                  callback(new Error('至少需要添加一个食材'));
                } else {
                  // 检查每个食材是否填写完整
                  const isValid = value.every(item => {
                    return item.ingredientsId && item.num;
                  });
                  if (!isValid) {
                    callback(new Error('请填写完整的食材和用量'));
                  } else {
                    callback();
                  }
                }
              },
              trigger: 'blur'
            }
          ]
          // num heat
        },
      }
    },
    created() {
      this.fetchData()
      this.dictdata()
      this.infredient()
    },
    methods: {
      async dictdata() {
        const res = await listData({
            dictType: "cuisine_column",
            pageSize: 99,
            pageNum:1
           })
           console.log(res)
        this.dictData = res.rows

        const T = JSON.parse(JSON.stringify(res.rows));
        const U = {}
        T.forEach(el => {
          U[el.dictLabel] = el.dictValue
        })

        this.tableColumn = U;
        console.log(this.tableColumn)
      },
      async onchangeSwitch(e,item) {
        console.log(e, item)
        const res = await updateData(item);
        if (res.code == 200) {
          this.dictdata()
          this.$message.success('操作成功');
        }
      },
         // 提交上传文件
     submitFileForm() {
      this.$refs.upload.submit()
    },
      /** 导出按钮操作 */
      handleExport() {
      this.download('food/dish/export', {
        ...this.searchForm
      }, `菜品导出${new Date().toISOString().slice(0, 10)}.xlsx`)
      },

      parseFileList(aptUrl) {
    try {
      if (!aptUrl) return [];
      
      if (typeof aptUrl === 'string') {
        try {
          const parsed = JSON.parse(aptUrl);
          return Array.isArray(parsed) ? parsed : [];
        } catch (e) {
          return aptUrl.split(',')
            .filter(url => url.trim())
            .map(url => ({ url: url.trim(), name: url.split('/').pop() || '文件' }));
        }
      }
      
      return Array.isArray(aptUrl) ? aptUrl : [];
    } catch (e) {
      console.error('解析文件列表失败:', e);
      return [];
    }
  },
  
  // 判断是否是图片
  isImage(file) {
    if (!file || !file.url) return false;
    const imageExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp'];
    const url = file.url.toLowerCase();
    return imageExtensions.some(ext => url.includes(ext));
  },
  
  // 获取预览列表（仅图片）
  getPreviewList(aptUrl) {
    return this.parseFileList(aptUrl)
      .filter(file => this.isImage(file))
      .map(file => file.url);
  },
      handleImport() {
      this.upload.title = "菜品导入"
      this.upload.open = true
      },
      importTemplate() {
      // const link = document.createElement('a');
      // link.href = '/菜品导入模板.xlsx'; // 路径相对于 public
      // link.download = '菜品导入模板.xlsx'; // 下载后的文件名
      // document.body.appendChild(link);
      // link.click();
        // document.body.removeChild(link);
      nameding.name("caipin.xlsx",false)
    },
        // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      this.getList()
    },
      deleteFoodItems(item,index) {
        this.form.foodIngredientsDishList.splice(index, 1); // 从 index 位置删除 1 个元素
      },
      beforeUpload(file) {
    const isImage = file.type.includes('image/');
    const isLt5M = file.size / 1024 / 1024 < 5;
    
    if (!isImage) {
      this.$message.error('只能上传图片文件！');
    }
    if (!isLt5M) {
      this.$message.error('图片大小不能超过5MB！');
    }
    
    return isImage && isLt5M;
  },
// 检查食材是否已被其他项选中
isIngredientDisabled(ingredientsId, currentIndex) {
    return this.form.foodIngredientsDishList.some((item, index) => 
      index !== currentIndex && item.ingredientsId === ingredientsId
    );
  },
  
  // 处理食材选择变化
  handleIngredientChange(currentIndex) {
    const currentItem = this.form.foodIngredientsDishList[currentIndex];
    if (!currentItem.ingredientsId) return;
    
    // 检查是否有重复
    const isDuplicate = this.form.foodIngredientsDishList.some((item, index) => 
      index !== currentIndex && item.ingredientsId === currentItem.ingredientsId
    );
    
    if (isDuplicate) {
      this.$message.error('该食材已被选择，请选择其他食材');
      currentItem.ingredientsId = ''; // 重置选择
    }
  },
  async handleImageChange(file, fileList) {
      this.fileList = fileList;
      if (file.status === 'ready') {
        try {
          const formData = new FormData();
          formData.append('file', file.raw);
          console.log(file)
          const response = await uploading(formData);
          if (response.code === 200) {
            // 更新当前文件的上传状态和URL
            const index = this.fileList.findIndex(item => item.uid === file.uid);
            if (index !== -1) {
              this.$set(this.fileList[index], 'url', response.data);
              this.$set(this.fileList[index], 'name', file.name);
              this.$set(this.fileList[index], 'status', 'success');
            }
            
            // 更新form.aptUrl，包含所有图片URL
            const urls = this.fileList.map(item => item.url || item.response?.data).filter(url => url);
            console.log(this.fileList)
            console.log(urls)
            // this.form.aptUrl = urls.join(',');
            this.form.image = JSON.stringify(this.fileList)
            
            this.$message.success('图片上传成功');
          } else {
            throw new Error(response.data || '上传失败');
          }
        } catch (error) {
          console.error('上传失败:', error);
          this.$message.error(error.message);
          // 移除上传失败的文件
          this.fileList = this.fileList.filter(item => item.uid !== file.uid);
        }
      }
    },
      async infredient() {
        const data = await getlists({ pageNum: 1, pageSize: 99999999 })
        this.ingredientList = data.rows
      },
      
      getStatusType(status) {
        const statusMap = {
          '0': 'success',  // 停用
          '1': 'danger', // 正常
          '2': 'warning', // 淘汰
          '3': 'info'     // 其他状态
        }
        return statusMap[status] || ''
      },
      getStatusText(status) {
        const statusTextMap = {
          '0': '正常',
          '1': '停用',
          '2': '淘汰'
        }
        return statusTextMap[status] || '未知'
      },
      inputGroup() {
       if (this.radio == 2) {
         this.searchForm.status = '0'
          this.searchForm.type = ''
        } else if (this.radio == 3) {
         this.searchForm.status = '2'
          this.searchForm.type = ''
        } else if (this.radio == 4) {
         this.searchForm.status = '1'
          this.searchForm.type = ''
       } else if (this.radio == 5) {
         this.searchForm.status = ''
          this.searchForm.type = '1'
       } else if (this.radio == 6) {
         this.searchForm.status = ''
          this.searchForm.type = '2'
       } else if (this.radio == 7) {
         this.searchForm.status = ''
          this.searchForm.type = '3'
        }else {
          this.searchForm.status = ''
        }
        this.fetchData()
      },
      // 获取菜品列表
      async fetchData() {
        this.loading = true
        try {
          const params = {
            ...this.searchForm,
            pageNum: this.pagination.pageNum,
            pageSize: this.pagination.pageSize
          }
          
          const data = await getList(params)

       
          this.tableData = data.rows
          this.tabhanderObj = this.tableData[0]
          this.pagination.total = data.total
        } catch (error) {
          console.error(error)
          this.$message.error('获取菜品列表失败')
        } finally {
          this.loading = false
        }
      },
      
      // 搜索
      handleSearch() {
        this.pagination.pageNum = 1
        this.fetchData()
      },
      
      // 重置搜索
      resetSearch() {
        this.$refs.searchForm.resetFields()
        this.radio = 1
        this.searchForm.status = ''
        this.handleSearch()
      },

      handleRemove(file, fileList) {
      this.fileList = fileList;
      // 更新form.aptUrl，移除被删除的图片URL
      const urls = this.fileList.map(item => item.url || item.response?.data);
      console.log(this.fileList)
      this.form.image = JSON.stringify(this.fileList)
    },
      
      // 分页大小变化
      handleSizeChange(val) {
        this.pagination.pageSize = val
        this.fetchData()
      },
      
      // 当前页变化
      handleCurrentChange(val) {
        this.pagination.pageNum = val
        this.fetchData()
      },
      
      // 表格选择变化
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      
      // 新增菜品
      handleAdd() {
        this.dialogTitle = '新增菜品'
        this.resetForm()
        this.dialogVisible = true
      },
      
      // 编辑菜品
      handleEdit(row) {
        this.dialogTitle = '编辑菜品'
        row.openingHours = []
        for (let index = 1; index <= 7; index++) {
          if (row["day" + index] == 1) {
            row.openingHours.push(index)
          }
      }
        this.form = JSON.parse(JSON.stringify(row))
        // if (this.form.image) {
        //   this.fileList = [{ name: '菜品图片', url: this.form.image }]
        // } else {
        //   this.fileList = []
        // }

        this.fileList = [];
          if (this.form.image) {
            const urls = JSON.parse(this.form.image);
            urls.forEach(url => {
              if (url) {
                this.fileList.push(url);
              }
            });
          }
        this.dialogVisible = true
      },
      
      // 批量编辑
      handleBatchEdit() {
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请至少选择一条记录')
          return
        }
        if (this.multipleSelection.length > 1) {
          this.$message.warning('暂不支持批量编辑')
          return
        }
        this.handleEdit(this.multipleSelection[0])
      },
      
      // 删除菜品
      handleDelete(row) {
        this.$confirm(`确定删除菜品【${row.foodName}】吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            await deleteDish(row.foodId)
            this.$message.success('删除成功')
            this.fetchData()
          } catch (error) {
            this.$message.error('删除失败')
          }
        }).catch(() => {})
      },
      
      // 批量删除
      handleBatchDelete() {
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请至少选择一条记录')
          return
        }
        const names = this.multipleSelection.map(item => item.foodName).join('、')
        this.$confirm(`确定删除选中的${this.multipleSelection.length}条记录吗?【${names}】`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            const ids = this.multipleSelection.map(item => item.foodId).join(',')
            await deleteDish(ids)
            this.$message.success('批量删除成功')
            this.fetchData()
          } catch (error) {
            this.$message.error('删除失败')
          }
        }).catch(() => {})
      },
      addIngredients() {
        this.form.foodIngredientsDishList.push(
            {
              ingredientsName: "",
              ingredientsId: "",
              ingredientsCode: "",
            foodId: "",
            num: null // 确保有 num 字段
            }
        )
      },
      // 重置表单
      resetForm() {
        this.form = {
          foodName: '',
          image: '',
          ingredients: '',
          allergy: '',
          peType: 0,
          huisType:0,
          calories: '',
          price: null,
          originalPrice: null,
          sales: null,
          portion: '',
          foodIngredientsDishList: [
            {
              ingredientsName: "",
              ingredientsId: "",
              ingredientsCode: "",
              foodId:""
            }
          ],
          taste: '',
          description: '',
          status: '0',
          createBy: this.$store.state.user.name,
          remark: '',
          params: {}
        }
        this.fileList = []
        this.$nextTick(() => {
          this.$refs.foodForm && this.$refs.foodForm.clearValidate()
        })
      },
      
      // 提交表单
      async handleSubmit() {
        try {
          await this.$refs.foodForm.validate()
          this.submitting = true
          
          // 设置创建人
          this.form.createBy = this.$store.state.user.name

          console.log(this.form)
          this.form.foodIngredientsDishList.forEach(els => {
            // console.log(el)
            if (els.ingredientsId) {
                // ingredientsId
              els.ingredientsName = this.ingredientList.filter(el => el.ingredientsId == els.ingredientsId)[0].ingredientsName;
            els.ingredientsCode = this.ingredientList.filter(el => el.ingredientsId == els.ingredientsId)[0].ingredientsCode
              els.unit = this.ingredientList.filter(el => el.ingredientsId == els.ingredientsId)[0].unit
              els.foodId = this.form.foodId
            if (!els.num) {
              els.num = 0
            }
            }
          })

          this.form.foodIngredientsDishList = this.form.foodIngredientsDishList.filter(el => el.ingredientsId)
              // 处理开放时间
            for (let index = 0; index < 8; index++) {
              this.form['day' + (index + 1)] = 0
          }
            if (!this.form.openingHours) {
              this.form.openingHours = []
            }
            this.form.openingHours.forEach(el => {
              this.form['day' + el] = 1
            })

            delete this.form.openingHours
          // {{ dict.type.foot_ingredient_type.filter(el=>el.value == ingredientList.filter(el=>el.ingredientsId == item.ingredientsId)[0].unit)[0].label }}
          if (this.form.foodId) {
            // 更新菜品
            await dishUpdate(this.form)
            this.$message.success('菜品更新成功')
          } else {
            // 新增菜品
            await dishAdd(this.form)
            this.$message.success('菜品新增成功')
          }
          
          this.dialogVisible = false
          this.fetchData()
        } catch (error) {
          if (error !== 'cancel') {
            console.error(error)
            this.$message.warning("请填写必填项")
          }
        } finally {
          this.submitting = false
        }
      }
    }
  }
  </script>
  
  <style scoped>
  /* 表头容器 */
.custom-header {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 0 4px;
}                                                     

/* 主标题 */
.header-title { 
  font-weight: 600;
  font-size: 14px;
  color: #333;
}

/* 状态指示器（基础样式） */
.status-indicator {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 2px 6px;
  border-radius: 10px;
  line-height: 1;
}

/* 已开启样式 */
.status-indicator.enabled {
  background: rgba(103, 194, 58, 0.1); /* 浅绿色背景 */
}
.status-indicator.enabled .status-dot {
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background: #67C23A; /* Element 绿色 */
}
.status-indicator.enabled .status-text {
  color: #67C23A;
}

/* 未开启样式 */
.status-indicator.disabled {
  background: rgba(192, 196, 204, 0.1); /* 浅灰色背景 */
}
.status-indicator.disabled .status-dot {
  width: 5px;
  height: 5px;
  border-radius: 50%;

  background: #C0C4CC; /* Element 灰色 */
}
.status-indicator.disabled .status-text {
  color: #909399;
}
.status-indicator.disabled .status-dot {
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background: #F56C6C;
}
.status-indicator.disabled .status-text {
  color: #F56C6C;
}

::v-deep .el-switch__label.is-active{
  color: #4C6EE2;
}

  ::v-deep .el-dialog__headerbtn .el-dialog__close{
  font-size: 25px;
}
  ::v-deep .el-dialog{
    border-radius: 15px;
  }
  ::v-deep .el-form--label-top .el-form-item__label{
   padding: 0;
  }
  .approval-container {
    padding: 20px;
    background: #fff;
  }
  
  .search-wrapper {
    margin-bottom: 20px;
  }
  
  .search-form {
    display: flex;
    flex-direction: column;
  }
  
  .search-row {
    display: flex;
    margin-bottom: 15px;
  }
  
  .search-row .el-form-item {
    margin-right: 20px;
    margin-bottom: 0;
  }
  
  .search-actions {
    margin-left: auto;
    /* padding-right: 10px; */
  }
  
  .status-filter {
    margin-bottom: 15px;
  }
  
  .table-wrapper {
    margin-top: 20px;
  }
  
  .content-cell {
    padding: 5px 0;
  }
  
  .content-cell p {
    margin: 5px 0;
    line-height: 1.5;
  }

  ::v-deep .el-dialog__body{
  padding-top: 8px;
}
  
  .pagination {
    margin-top: 20px;
    text-align: right;
  }
  
  .el-table::before {
    display: none;
  }
  
  .el-table {
    border: none;
  }
  
  .el-table /deep/ th {
    border-bottom: 1px solid #ebeef5;
  }
  
  .el-table /deep/ td {
    border-bottom: 1px solid #ebeef5;
  }
  
  .el-input-number {
    width: 100%;
  }
  
  ::v-deep .el-radio__input.is-checked .el-radio__inner {
    background-color: #4C6EE2;
    border: 1px solid #4C6EE2;
    color: black;
  }
  
  ::v-deep .el-radio__input.is-checked + .el-radio__label {
    color: black;
  }
  
  ::v-deep .el-form-item {
    margin-bottom: 8px;
    margin-right:0;
  }
  
  ::v-deep .el-input--medium .el-input__inner {
    height: 32px;
    line-height: 32px;
    border-radius: 8px;
    background: rgba(0, 0, 0, 0);
    box-sizing: border-box;
    border: 1px solid rgba(0, 0, 0, 0.2);
  }

  ::v-deep .dialogN .el-input--medium .el-input__inner {
    height: 42px;
    line-height: 42px;
    border-radius: 8px;
    background: rgba(0, 0, 0, 0);
    box-sizing: border-box;
    border: 1px solid rgba(0, 0, 0, 0.2);
  }
  </style>